package com.vma.user.vo;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import java.io.Serializable;

/**
 * 短信验证码对象
 * 
 * @author tangcc
 * @date 2016年3月15日
 */
public class SmsCode implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2737426050572895959L;

	private final static Logger logger = Logger.getLogger(SmsCode.class);

	/**
	 * 发送验证码手机号码
	 */
	private String mobile;

	/**
	 * 短信验证码
	 */
	private String smsCode;

	/**
	 * 生成验证码系统时间戳
	 */
	private long currentSystemTime;

	/**
	 * 验证错误次数
	 */
	private int errorTime = 0;

	/**
	 * 使用手机号生成短信验证码对象
	 * 
	 * @param mobile
	 */
	public SmsCode(String mobile) {
		this.mobile = mobile;
		this.smsCode = generateSmsCode();
		this.currentSystemTime = System.currentTimeMillis();
		this.errorTime = 0;
	}

	private String generateSmsCode() {
		return  RandomStringUtils.random(6, false, true);
	}

	/**
	 * 验证输入的短信验证码
	 * 
	 * @param inputMobile
	 * @param inputCode
	 * @return
	 */
	public boolean valid(String inputMobile, String inputCode) {
		if (!isAvailable()) {
			return false;
		}
		if (!this.mobile.equals(inputMobile)) {
			logger.error("手机号不匹配");
			this.errorTime++;
			return false;
		} else if (!this.smsCode.equals(inputCode)) {
			logger.error("验证码错误");
			this.errorTime++;
			return false;
		} else {
			return true;
		}
	}

	private boolean isAvailable() {
		Long inputTime = System.currentTimeMillis();
		if (inputTime - this.currentSystemTime > 120000) {
			logger.error("验证码已超时");
			return false;
		}

		if (this.errorTime >= 6) {
			logger.error("已输错6次");
			return false;
		}
		return true;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getSmsCode() {
		return smsCode;
	}

	public void setSmsCode(String smsCode) {
		this.smsCode = smsCode;
	}

	public long getCurrentSystemTime() {
		return currentSystemTime;
	}

	public void setCurrentSystemTime(long currentSystemTime) {
		this.currentSystemTime = currentSystemTime;
	}

	public int getErrorTime() {
		return errorTime;
	}

	public void setErrorTime(int errorTime) {
		this.errorTime = errorTime;
	}
}
